package com.cs.dingdingauto

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.util.Log
import androidx.work.*
import kotlinx.coroutines.delay
import java.net.URLEncoder
import java.util.concurrent.TimeUnit

/**
 * @author liguandong
 * @data 2023/7/4
 *
 */
class DingDingWork(val appContext: Context, workerParams: WorkerParameters):
    CoroutineWorker(appContext, workerParams) {
    override suspend fun doWork(): Result {
        Log.i("lgd", "触发调起钉钉")
        val dingding = "com.alibaba.android.rimet"
        try {
            val request = OneTimeWorkRequestBuilder<LaunchAppWork>() // Additional configuration
                .setInitialDelay(15, TimeUnit.SECONDS).build()
            val code = WorkManager.getInstance(appContext).enqueue(request)
            //            appContext.packageManager.getApplicationInfo(name, PackageManager.GET_UNINSTALLED_PACKAGES)
//            val packageManager = appContext.packageManager
//            val intent = packageManager.getLaunchIntentForPackage(name)
//            appContext.startActivity(intent)
            DingDingHelper.launchDingDing()
            Log.i("lgd", "doWork: DingDingWork 10s后 调起自身${code.result} ${code.state.toString()}")
        } catch (e: PackageManager.NameNotFoundException) {
        }
        return Result.success()
    }



    /**
     * 打开钉钉客户端 并在钉钉客户端打开传入的指定url
     * @param context 安卓上下文环境，推荐Activity Context
     * @param url 需要在钉钉客户端打开的页面地址
     */
    private fun startDingtalkApp(context: Context, url: String) {
        val intent = Intent(Intent.ACTION_VIEW)
        val jumpUrl = "dingtalk://dingtalkclient/page/link?url=" + URLEncoder.encode(url) //必须对url做encode
        val uri: Uri = Uri.parse(jumpUrl)
        intent.data = uri
        if (null != intent.resolveActivity(context.getPackageManager())) {
            context.startActivity(intent)
        }
    }
}
